/**
 *
 */

package lohmar.ashar.android.batterySaver.widget;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.os.BatteryManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.widget.RemoteViews;

import lohmar.ashar.android.batterySaver.R;
import lohmar.ashar.android.batterySaver.profile.Profile;
import lohmar.ashar.android.batterySaver.profile.ProfileFactory;
import lohmar.ashar.android.batterySaver.profile.ProfileManager;

/**
 * @author Mihai HARAS (Lohmar ASHAR) 2011
 */
public class WidgetProvider extends AppWidgetProvider {

    private static int               level              = -2;
    private static int               scale              = -2;
    private static boolean           isPlugged          = false;

    private static BroadcastReceiver registeredReceiver = null;

    @Override
    public void onDisabled(Context context) {
        super.onDisabled(context);
        unregisterAsReceiver(context);
    }

    @Override
    public void onEnabled(Context context) {
        super.onEnabled(context);
        registerAsReceiver(context);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) {
            int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            boolean isPlugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) > 0;
            if (WidgetProvider.level != level || WidgetProvider.scale != scale || WidgetProvider.isPlugged != isPlugged) {
                WidgetProvider.level = level;
                WidgetProvider.scale = scale;
                WidgetProvider.isPlugged = isPlugged;
                drawWidget(context);
            }
        } else if (intent.getAction().equals(ProfileManager.ACTION_PROFILE_STATE)) {
            drawWidget(context);
        }
        super.onReceive(context, intent);
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        super.onUpdate(context, appWidgetManager, appWidgetIds);
        registerAsReceiver(context);
        drawWidget(context);
        Intent i = new Intent(ProfileManager.ACTION_PROFILE_STATE);
        PendingIntent pi = PendingIntent.getBroadcast(context.getApplicationContext(), 0, i, 0);
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
        views.setOnClickPendingIntent(R.id.widget, pi);
        appWidgetManager.updateAppWidget(appWidgetIds, views);
    }

    private void drawWidget(Context context) {
        Bitmap b = Bitmap.createBitmap(72, 72, Config.ARGB_8888);
        Canvas c = new Canvas(b);
        BitmapDrawable bg = (BitmapDrawable) context.getResources().getDrawable(R.drawable.w_bg);
        bg.setBounds(0, 0, 72, 72);
        bg.draw(c);
        Profile p = ProfileFactory.getDefaultProfile();
        int pIcon = p.getIconId();
        if (p.isEnabled()) {
            BitmapDrawable sel = (BitmapDrawable) context.getResources().getDrawable(R.drawable.sel);
            sel.setGravity(Gravity.NO_GRAVITY);
            sel.setBounds(18, 32, 53, 36);
            sel.draw(c);
            pIcon = p.getEnabledIconId();
        }
        BitmapDrawable profileIcon = (BitmapDrawable) context.getResources().getDrawable(pIcon);
        profileIcon.setGravity(Gravity.NO_GRAVITY);
        profileIcon.setBounds(25, 6, 48, 34);
        profileIcon.draw(c);
        if (isPlugged) {
            BitmapDrawable ac = (BitmapDrawable) context.getResources().getDrawable(R.drawable.light);
            ac.setGravity(Gravity.NO_GRAVITY);
            ac.setBounds(60, 6, 65, 14);
            ac.draw(c);
        }
        Bitmap b2 = Bitmap.createBitmap(64, 25, Config.ARGB_8888);
        b2.setDensity(DisplayMetrics.DENSITY_HIGH);

        BatteryView batteryView = new BatteryView(context);
        batteryView.setTextSize(12);
        batteryView.setBatteryLevel((float) level / scale);
        batteryView.setSize(64, 25);
        batteryView.draw(new Canvas(b2));
        BitmapDrawable b3 = new BitmapDrawable(b2);
        b3.setBounds(5, 45, 68, 68);
        b3.draw(c);

        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
        views.setImageViewBitmap(R.id.batValWidget, b);
        ComponentName thisWidget = new ComponentName(context, WidgetProvider.class);
        if (thisWidget != null) {
            AppWidgetManager manager = AppWidgetManager.getInstance(context);
            if (manager != null) {
                manager.updateAppWidget(thisWidget, views);
            }
        }
    }

    private void registerAsReceiver(Context context) {
        if (registeredReceiver == null) {
            try {
                context.getApplicationContext().registerReceiver(this, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
                registeredReceiver = this;
            } catch (Exception e) {
                Log.e("", "", e);
            }
        }
    }

    private void unregisterAsReceiver(Context context) {
        try {
            if (registeredReceiver != null) {
                context.unregisterReceiver(registeredReceiver);
                registeredReceiver = null;
            }
        } catch (Exception e1) {
            Log.e("", "first try", e1);
            try {
                if (registeredReceiver != null) {
                    context.getApplicationContext().unregisterReceiver(registeredReceiver);
                    registeredReceiver = null;
                }
            } catch (Exception e2) {
                Log.e("", "second try", e2);
            }
        }
    }

}
